// reduxDemo.js
import { configureStore, createSlice } from '@reduxjs/toolkit';
import { Provider, useDispatch, useSelector } from 'react-redux';

// 1. 创建一个 slice（包含状态和修改方法）
const counterSlice = createSlice({
  name: 'counter',
  initialState: { value: 0 },
  reducers: {
    increment: state => { state.value += 1 },
    decrement: state => { state.value -= 1 },
  }
});

// 2. 创建 store
const store = configureStore({
  reducer: { counter: counterSlice.reducer }
});

// 3. 组件中使用 Redux
function Counter() {
  const count = useSelector(state => state.counter.value);
  const dispatch = useDispatch();
  return (
    <div>
      <button onClick={() => dispatch(counterSlice.actions.decrement())}>-</button>
      <span style={{margin: '0 12px'}}>{count}</span>
      <button onClick={() => dispatch(counterSlice.actions.increment())}>+</button>
    </div>
  );
}

// 4. 用 Provider 包裹组件
export default function ReduxDemo() {
  return (
    <Provider store={store}>
      <h2>Redux 计数器示例</h2>
      <Counter />
    </Provider>
  );
}
